package oop.db.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import oop.db.Database;

public class QuestionAnswerDAO {

	public static void addAnswer(long questionId, long answerId, boolean correct) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "INSERT INTO tblQuestionAnswer (ques_id,ans_id,correct) VALUES (?,?,?)";
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, questionId);
			stmt.setLong(2, answerId);
			stmt.setBoolean(3, correct);
			stmt.executeUpdate();
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}
	
	public static void removeAnswer(long questionId, long answerId) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "DELETE FROM tblQuestionAnswer WHERE ques_id="+questionId+" AND ans_id="+answerId;
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.executeUpdate();
			stmt.close();
			
			sql = "DELETE FROM tblAnswer WHERE ans_id="+answerId;
			stmt = conn.prepareStatement(sql);
			stmt.executeUpdate();
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public static int persistAnswer(long questionId, long answerId,
			boolean correct) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "UPDATE tblQuestionAnswer SET "
					+ "correct=? "
					+ "WHERE ques_id = ? AND ans_id = ?";

			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setBoolean(1, correct);
			stmt.setLong(2, questionId);
			stmt.setLong(3, answerId);
			return stmt.executeUpdate();
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

}
